<template>
    <div class="app-container">
  
      <!-- 查询和其他操作 -->
      <el-form :inline="true" class="demo-form-inline filter">
        <el-form-item label="客户名称">
          <el-select v-model="listQuery.fsiteNo" :disabled="this.$store.state.user.fsiteLevel==3" clearable filterable placeholder="请选择客户名称">
              <el-option
                v-for="item in fsiteNoBelongOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
        </el-form-item>
        <el-form-item label="分类名称">
        <el-input v-model="listQuery.fclassstname" clearable class="filter-item" style="width: 200px;" placeholder="请输入分类名称"/>
        </el-form-item>
          <el-form-item label="上级分类">
            <el-select
                  v-model="listQuery.fparentno"
                  class="filter-item"
                  clearable
                  placeholder="请选择上级分类"
                >
                  <el-option
                    v-for="item in fparentnoOptions"
                    :key="item.fclassstno"
                    :label="item.fclassstname"
                    :value="item.fclassstno"
                  />
                </el-select>
          </el-form-item>
        <el-form-item>
          <el-button round size="medium" class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" @click="handleFilter">查找</el-button>
          <el-button round size="medium" class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" @click="handleCreate">添加</el-button>
          <el-button round size="medium" :style="{background:buttonColor.import,color:buttonColor.color}" @click="handleUpload">导入</el-button>
        </el-form-item>
        </el-form>
  
      <!-- 查询结果 -->
      <el-table :height="buttonColor.clientHeight" v-loading="listLoading" :data="list" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
           <el-table-column align="center" :width="buttonColor.operationTwo" label="操作" class-name="small-padding">
          <template slot-scope="scope">
             <div class="operationButton">
              <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" />
              编辑
            </div>
            <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" />
              删除
            </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :index="indexMethod" width="108" align="center" label="序号" type="index" />
        <el-table-column align="left" label="分类编号" width="271" prop="fclassstno" />
        <el-table-column align="left" label="分类名称" prop="fclassstname" />
        <el-table-column :formatter="formatfparentno" width="298" align="left" label="上级分类" prop="fparentno" />
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <!-- 添加或修改对话框 -->
      <el-dialog width="450px" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
        <template slot="title">
        <div :style="titleColor">{{textMap[dialogStatus]}}</div>
      </template>
        <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="80px" style="width: 400px; margin:0 30px;">
          <el-form-item class="required" label="分类编号" prop="fclassstno">
            <el-input v-if="dialogStatus=='create'" v-model="dataForm.fclassstno"/>
            <el-input v-else disabled v-model="dataForm.fclassstno"/>
          </el-form-item>
          <el-form-item class="required" label="分类名称" prop="fclassstname">
            <el-input v-model="dataForm.fclassstname"/>
          </el-form-item>
          <el-form-item label="上级分类" prop="fparentno">
            <el-select
                  v-model="dataForm.fparentno"
                  class="filter-item"
                  clearable
                >
                  <el-option
                    v-for="item in fparentnoOptions"
                    :key="item.fclassstno"
                    :label="item.fclassstname"
                    :value="item.fclassstno"
                  />
                </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
          <el-button round v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
          <el-button round v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
        </div>
      </el-dialog>
  
        <!-- 导出弹窗 -->
      <el-dialog width="auto" :close-on-click-modal="false" :visible.sync="uploadVisible">
        <template slot="title">
        <div :style="exportColor">物料分类</div>
      </template>
        <div style="width:300px;height:200px;display: flex;flex-direction: column;align-items: center">
              <el-upload
            :on-success="uploadFileSuccess"
            :headers="headers"
            :action="uploadPath2"
            :data="{'tableName':'Import_i_ts_good_class'}"
            :show-file-list="false"
            class="filter-item"
            style="margin-top:20px"
            accept=".xlsx">
            <el-button round size="medium" icon="el-icon-upload" :style="{background:buttonColor.import,color:buttonColor.color}">导入</el-button>
          </el-upload>
          <div style="margin-top:30px;text-decoration:underline">
            <a :href="downUrl" style="color: blue">模板文件下载</a>
          </div>
  
        </div>
      </el-dialog>
    </div>
  </template>
  
  <style>
    .button-margin {
      margin : 2px 0px;
    }
    .el-button+.el-button {
      margin-left: 1px;
    }
  </style>
  
  <script>
  import { listgoodClass, creategoodClass, updategoodClass, deletegoodClass } from '@/api/haocai/goodClass'
  import { fsiteOptionsByLevel, getListArea, uploadPath2 } from '@/api/area'
  import { getToken } from '@/utils/auth'
  import Pagination from '@/components/Pagination'
  import moment from 'moment'
  import { tableColor,titleColor,exportColor,buttonColor } from '@/filters/index'
  import { getApiUrl } from '@/utils/request'
  export default {
    name: 'ITsGoodClass',
    components: { Pagination },
    data() {
      return {
        fsiteNoBelongOptions: [], // 客户列表
        downUrl: null,
        uploadVisible: false,
        uploadPath2,
        buttonColor:buttonColor,
        fparentnoOptions: [],
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          fsiteNo: this.$store.state.user.fsiteNo,
          fclassstname: undefined,
          fparentno: undefined,
          fclassstyle: undefined,
          flevel: undefined,
          feffday: undefined,
          fupddate: undefined,
          foperator: undefined,
          sort: 'create_time',
          order: 'desc'
        },
        dataForm: {
          fsiteNo: undefined,
          fclassstno: undefined,
          fclassstname: undefined,
          fparentno: undefined,
          fclassstyle: undefined,
          flevel: undefined,
          feffday: undefined,
          fupddate: undefined,
          foperator: undefined,
          id: undefined
        },
        tableColor,
        titleColor,
        exportColor,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          fclassstname: [
            { required: true, message: '分类名称不能为空' },
          ],
          fclassstno: [
            { required: true, message: '分类编号不能为空' },
          ],
          fparentno: [],
          fclassstyle: [
            { type: 'number', message: '分类类别必须为数字值' },
          ],
          flevel: [
            { type: 'number', message: '分类级别必须为数字值' },
          ],
          feffday: [
            { type: 'number', message: '保质期必须为数字值' },
          ],
          fupddate: [ ],
          foperator: [],
        }
      }
    },
    created() {
      console.log('object111',moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
      this.getList()
      this.downUrl = getApiUrl() + 'xlsx/1-1物料分类.xlsx'
      // 客户列表
      fsiteOptionsByLevel(3)
        .then(response => {
          this.fsiteNoBelongOptions = response.data.data.list
        })
        .catch(() => {
          this.fsiteNoBelongOptions = []
        })
      // 上级分类
      this.getcat();
      // getListArea({ flag: 29,arg1: this.$store.state.user.fsiteNo })
      //   .then(response => {
      //     this.fparentnoOptions = response.data.data.list
      //   })
      //   .catch(() => {
      //     this.fparentnoOptions = []
      //   })
    },
    computed: {
      headers() {
        return {
          'Authorization': getToken()
        }
      }
    },
    methods: {
      //分类
      getcat(){
        listgoodClass(this.listQuery)
          .then(response => {
            this.fparentnoOptions = response.data.data.list
          })
          .catch(() => {
            this.fparentnoOptions = []
          })
      },
      datetimeFormat(row, column) {
        const date = row[column.property]
        if (date === undefined || date === null) {
          return ''
        }
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
      },
      uploadFileSuccess: function(response) {
        this.uploadVisible = false
        this.$notify.success({
          title: '导入',
          dangerouslyUseHTMLString:true,
          message: response.data
        })
      },
       handleUpload(){
        this.uploadVisible = true
      },
      // 上级分类
      formatfparentno: function(row, column) {
        if (this.fparentnoOptions.length > 0) {
          for (let i = 0; i < this.fparentnoOptions.length; i++) {
            if (row.fparentno === this.fparentnoOptions[i].fclassstno) {
              return this.fparentnoOptions[i].fclassstname
            }
          }
          return ''
        } else {
          return ''
        }
      },
      getList() {
        this.listLoading = true
        listgoodClass(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          fclassstno: undefined,
          fclassstname: undefined,
          fparentno: undefined,
          fclassstyle: undefined,
          flevel: undefined,
          feffday: undefined,
          fupddate: undefined,
          foperator: undefined,
          id: undefined
        }
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            creategoodClass(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加物料分类成功'
                })
                this.getcat();
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updategoodClass(this.dataForm, this.$route.query.id)
              .then(() => {
                for (const v of this.list) {
                  if (v.fclassstno === this.dataForm.fclassstno) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新物料分类成功'
                })
                this.getcat();
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('是否要删除物料分类', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletegoodClass(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除耗材分类成功'
              })
              this.getcat();
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data
              })
            })
        }).catch(()=>{})
      },
      indexMethod(index) {
        index = index + 1
        return index
      }
    }
  }
  </script>
  